package com.chapp.lastFmWs.parser;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

import android.sax.Element;
import android.sax.ElementListener;
import android.sax.EndTextElementListener;
import android.sax.TextElementListener;
import android.util.Log;

import com.chapp.base.Artist;
import com.chapp.lastFmWs.parser.base.SearchBaseParser;

public class ArtistSearchParser extends SearchBaseParser<Artist> {
	private String tag = getClass().getName();

	private Element elementArtist = elementResults.getChild("artistmatches")
			.getChild("artist");

	private Artist artist;

	@Override
	protected void createListeners() {
		Log.d(tag, "creando artist listener");
		super.createListeners();
		elementArtist.setElementListener(new ElementListener() {

			@Override
			public void end() {
				response.addSearchedItem(artist);
			}

			@Override
			public void start(Attributes attributes) {
				artist = new Artist();
			}
		});

		elementArtist.getChild("name").setEndTextElementListener(
				new EndTextElementListener() {
					@Override
					public void end(String body) {
						artist.setName(body);
					}
				});

		// <image
		// size="medium">http://userserve-ak.last.fm/serve/64/33623311.png</image>
		elementArtist.getChild("image").setTextElementListener(
				new TextElementListener() {
					String size;;

					@Override
					public void end(String body) {
						if (size.equals("large") && body != null
								&& !body.equals(""))
							artist.setThumbnailURL(body);
					}

					@Override
					public void start(Attributes attributes) {
						size = attributes.getValue(0);
					}
				});
		Log.d(tag, "FIN creando artist listene");
	}

	public SearchResponse<Artist> parse(String xml) {
		Log.d(tag, "init parse " + xml);
		// try {
		// Xml.parse(xml, rootLmf.getContentHandler());
		// } catch (SAXException e) {
		try {
			parseXml(xml);
		} catch (SAXException e) {
			Log.e(tag, "Error Parsing XML.", e);
			return null;
		}

		if (!statusOk) {
			response.setError(error);
		}
		Log.d(tag, "fin parse");
		return response;
	}
}
